<script setup name="DocMy">
import SelectTemplateList from "@/views/common/selectTemplateList.vue";
import {useRoute} from "vue-router";
import {filemakerctrl} from "js-pageoffice";
import {addDoc, deleteDoc, getDocMyTemplatePageList} from "@/api/document/myDocument.js";
import DocumentList from "@/views/document/my/documentList.vue";
import SelectDeptList from "@/views/document/my/selectDeptList.vue";
import {selectTemplateFunctions} from "@/utils/selectTemplate.js";
import {tabFunctions} from "@/utils/tab.js";
import {deptFunctions} from "@/utils/document-my.js";

const {proxy} = getCurrentInstance()
const {docStatus, urgency, secretLevel} = proxy.useDict(["docStatus", true], ["urgency", false], ["secretLevel", false])
const addOpen = ref(false)
const addTitle = ref('')
const loading = ref(false)
const isDisabledButtons = ref(false)
const route = useRoute()
const activeTabName = ref(route.query?.docStatus || '')
const upload = reactive({
  isUploading: false
})
const isAllowCopy = ref(true)
const isWaterMark = ref(true)
const data = reactive({
  addForm: {
    printCount: 1,
  },
  rules: {
    subject: [{ required: true,  message: "发文标题不能为空", trigger: 'change'}],
    templateName: [{ required: true,  message: "公文模板不能为空", trigger: 'change'}],
    urgency: [{ required: true,  message: "请选择紧急程度", trigger: 'change'}],
    secretLevel: [{ required: true,  message: "请选择密级", trigger: 'change'}],
    sendUnit: [{ required: true,  message: "请选择发文单位", trigger: 'manual'}]
  }
})
const {addForm, rules} = toRefs(data)
const documentListRefs = ref([])
const templateListOpen = ref(false)
const deptListOpen = ref(false)
let deptOpProp = {}
const customReadonlyInputStyle = ref({cursor: 'not-allowed'})
const {
  openTemplateDialog,
  closeTemplateDialog,
  getTemplateList
} = selectTemplateFunctions(getDocMyTemplatePageList, '选择公文模板', templateListOpen)
const {
  handChangeTab,
  handClickTab,
  loopSetRef
} = tabFunctions(activeTabName, documentListRefs)
const {
  openDeptDialog,
  closeDeptDialog,
  getDeptList,
  handleSelectedDept,
  clearSendUnit,
  clearMainSendUnits,
  clearCopySendUnits
} = deptFunctions(deptListOpen, deptOpProp, addForm)

onActivated(() => {
  const docStatus = route.query.docStatus
  if (docStatus != null) {
    handChangeTab(docStatus)
  }
})

/** 重置操作表单 */
function reset() {
  addForm.value = {
    isAllowCopy: '否',
    isWaterMark: '是',
    templateId: null,
    templateName: '',
    templateListOpen: false,
    urgency: '',
    secretLevel: '',
    mainSendUnitIds: null,
    mainSendUnits: '',
    copySendUnitIds: null,
    copySendUnits: '',
    printCount: 1
  }
  proxy.resetForm("addFormRef")
}

/** 取消按钮 */
function cancel() {
  reset()
  addOpen.value = false
}

/** 新增按钮操作 */
function handleAdd() {
  reset()
  addOpen.value = true
  addTitle.value = "新建公文"
}

function setBackdropOrDisableForDialog(isBackdropOrDisable) {
  upload.isUploading = isBackdropOrDisable
  loading.value = isBackdropOrDisable
  isDisabledButtons.value = isBackdropOrDisable
}

function wordAutoFill(docId) {
  //填充呈批表
  filemakerctrl.SaveFilePage = '/doc/my/updateApprovalWord/' + docId
  filemakerctrl.CallFileMaker({
    url: "/doc/my/approvalAutoFill/" + docId,
    success: function () {
      //填充正文
      filemakerctrl.SaveFilePage = '/doc/my/updateMainWord?id=' + docId
      filemakerctrl.CallFileMaker({
        url: "/doc/my/mainAutoFill/" + docId,
        success: function () {
          addOpen.value = false
          setBackdropOrDisableForDialog(false)
          proxy.$modal.alertSuccess('保存成功')
          refreshList()
        },
        error: function (msg) {
          wordAutoFillFail(msg)
        }
      })
    },
    error: function (msg) {
      wordAutoFillFail(msg)
    }
  })
  function wordAutoFillFail(msg) {
    setBackdropOrDisableForDialog(false)
    deleteDoc(docId)
    proxy.$modal.alertError(msg)
  }
}

/** 新建公文保存 */
function saveDoc() {
  proxy.$refs["addFormRef"].validate(valid => {
    if (valid) {
      setBackdropOrDisableForDialog(true)
      addDoc(addForm.value).then((docId) => {
        wordAutoFill(docId)
      }).catch(() => {
        setBackdropOrDisableForDialog(false)
      })
    }
  })
}

function refreshList() {
  activeTabName.value = '拟稿'
  if (documentListRefs.value.length > 0) {
    documentListRefs.value[1].resetQuery()
  }
}

function handleSelectedTemplate(template) {
  addForm.value.templateId = template.id
  addForm.value.templateName = template.name
  templateListOpen.value = false
}

const changIsAllowCopy = (val) => {
  isAllowCopy.value = val
}

const changIsWaterMark = (val) => {
  isWaterMark.value = val
}
</script>

<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--公文数据-->
      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button
                type="primary"
                plain
                icon="Plus"
                @click="handleAdd"
                v-hasPermi="['doc:my:add']"
            >新增
            </el-button>
          </el-col>

        </el-row>
        <el-tabs v-model="activeTabName" class="demo-tabs" @tab-change="handChangeTab" @tab-click="handClickTab">
          <template v-for="(status, index) in docStatus" :key="status.value">
            <el-tab-pane :name="status.value"
                         :label="status.label"
                         lazy
                         style="padding-bottom: 10px;">
              <DocumentList :ref="loopSetRef(index)" :status="status.value" :docStatus="docStatus" v-if="activeTabName === status.value"/>
            </el-tab-pane>
          </template>
        </el-tabs>
      </el-col>
    </el-row>

    <!-- 添加公文对话框-->
    <el-dialog :title="addTitle" v-model="addOpen" width="1000px" append-to-body :close-on-click-modal="false">
      <el-form @submit.native.prevent :model="addForm" :rules="rules" ref="addFormRef" v-loading="loading" element-loading-text="正在保存，请稍后..." label-width="110px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="禁止拷贝公文" prop="isAllowCopy">
              <el-switch
                  v-model="addForm.isAllowCopy"
                  inline-prompt
                  active-text="禁止"
                  active-value="否"
                  inactive-text="允许"
                  inactive-value="是"
                  style="--el-switch-on-color: #529b2e; --el-switch-off-color: #6379bb"
                  @change="changIsAllowCopy"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="添加水印" prop="isWaterMark">
              <el-switch
                  v-model="addForm.isWaterMark"
                  inline-prompt
                  active-text="是"
                  active-value="是"
                  inactive-text="否"
                  inactive-value="否"
                  style="--el-switch-on-color: #529b2e; --el-switch-off-color: #6379bb"
                  @change="changIsWaterMark"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="紧急程度" prop="urgency">
              <el-select v-model="addForm.urgency" placeholder="请选择">
                <el-option
                    v-for="dict in urgency"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="密级" prop="secretLevel">
              <el-select v-model="addForm.secretLevel" placeholder="请选择">
                <el-option
                    v-for="dict in secretLevel"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发文标题" prop="subject">
              <el-input v-model="addForm.subject" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发文字号" prop="docNo">
              <el-input v-model="addForm.docNo" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公文模板" prop="templateName">
              <input type="hidden" v-model="addForm.templateId" />
              <el-input readonly :input-style="customReadonlyInputStyle" v-model="addForm.templateName" placeholder=""
                        style="width: 85%;"/>
              <el-button type="primary" @click="openTemplateDialog" style="margin-left: -2px; width: 15%;">请选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发文单位" prop="sendUnit">
              <el-input readonly :input-style="customReadonlyInputStyle" v-model="addForm.sendUnit" placeholder="" style="width: 85%;" >
                <template #suffix>
                  <el-icon class="el-input__icon" @click="clearSendUnit" style="color: #409EFF; cursor: pointer;"><CircleClose /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="openDeptDialog('sendUnit', '')" style="margin-left: -2px; width: 15%;">请选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="主送单位" prop="mainSendUnitIds">
              <input type="hidden" v-model="addForm.mainSendUnitIds" />
              <el-input readonly :input-style="customReadonlyInputStyle" v-model="addForm.mainSendUnits" placeholder="" style="width: 85%;">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="clearMainSendUnits" style="color: #409EFF; cursor: pointer;"><CircleClose /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="openDeptDialog('mainSendUnits', 'mainSendUnitIds')" style="margin-left: -2px; width: 15%;">请选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="抄送单位" prop="copySendUnitIds">
              <input type="hidden" v-model="addForm.copySendUnitIds" />
              <el-input readonly :input-style="customReadonlyInputStyle" v-model="addForm.copySendUnits" placeholder="" style="width: 85%;">
                <template #suffix>
                  <el-icon class="el-input__icon" @click="clearCopySendUnits" style="color: #409EFF; cursor: pointer;"><CircleClose /></el-icon>
                </template>
              </el-input>
              <el-button type="primary" @click="openDeptDialog('copySendUnits', 'copySendUnitIds')" style="margin-left: -2px; width: 15%;">请选择</el-button>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="公文摘要" prop="docPrecis">
              <el-input v-model="addForm.docPrecis" placeholder="" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="发文意见" prop="sendUnitAdvice">
              <el-input v-model="addForm.sendUnitAdvice" placeholder="" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="限办日期" prop="endDate">
              <el-date-picker
                  v-model="addForm.endDate"
                  type="date"
                  placeholder="选择日期"
                  clearable
                  style="width: 100%;"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="印发日期" prop="printDate">
              <el-date-picker
                  v-model="addForm.printDate"
                  type="date"
                  placeholder="选择日期"
                  clearable
                  style="width: 100%;"
                  value-format="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="印发机关" prop="printUnit">
              <el-input v-model="addForm.printUnit" placeholder="" clearable/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="印发份数" prop="printCount">
              <el-input v-model="addForm.printCount" placeholder="" clearable/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注信息">
              <el-input v-model="addForm.memo" type="textarea" placeholder="备注信息请勿超过255个 字符" maxlength="255"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <SelectTemplateList
          :is-open="templateListOpen"
          @getTemplateList="getTemplateList"
          @handleSelectedTemplate="handleSelectedTemplate"
          @close="closeTemplateDialog"
          templateType="docMyFileTemplate"/>
      <SelectDeptList
          :is-open="deptListOpen"
          @getDeptList="getDeptList"
          @handleSelectedDept="handleSelectedDept"
          @close="closeDeptDialog"/>

      <template #footer>
        <div class="dialog-footer">
          <el-button :disabled="isDisabledButtons" type="primary" @click="saveDoc">保 存</el-button>
          <el-button :disabled="isDisabledButtons" @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

  </div>
</template>
<style scoped>
.input-style {
  cursor: not-allowed;
}
</style>
